<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="my-tool-bar">
        <Toolbar
          :items="pageData.btnList"
          @add="addHandler"
          @del="deleteHandler"
          @select="selectHandler"
          @downloadApp="downloadApp"
          @downloadAppQrcode="downloadAppQrcodes"
        >
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <div class="w-full h-full">
        <encapsulation-agrid
          style="height: 100%"
          ref="gridOption"
          :configaggrid="configTable"
        ></encapsulation-agrid>
      </div>
      <!-- <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999"> -->

      <!-- <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%" :defaultColDef="defaultColDef"
          class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys> -->
      <!-- </a-spin> -->
    </template>
    <!-- <paginationCopys :total="total" show-total show-jumper show-page-size @change="PageSize" @page-size-change="change1"
      :page-size-options="optionsList" style="justify-content: center" :page-size="size" :current="page" /> -->
    <a-drawer
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="版本号"
            field="versionCode"
            :rules="[{ required: true, message: '版本号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="dataForm.versionCode" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="版本名称"
            field="versionName"
            :rules="[{ required: true, message: '版本名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="dataForm.versionName" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="版本信息"
            field="versionInfo"
            :rules="[{ required: true, message: '版本信息必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" v-model="dataForm.versionInfo" />
          </a-form-item>
          <!--                    <a-form-item label="版本类别" field="versionType" :rules="[{ required: true, message: '版本类别必填' }]"-->
          <!--                        :validate-trigger="['change', 'blur']">-->
          <!--                        <a-select popup-container="html"  class="bacClass" v-model="dataForm.versionType" allow-clear>-->
          <!--                            <a-option :value="0">内网</a-option>-->
          <!--                            <a-option :value="1">外网</a-option>-->
          <!--                        </a-select>-->
          <!--                    </a-form-item>-->
          <!-- <a-form-item label="更新包" field="file"
                        :validate-trigger="['change', 'blur']">
                        <input type="file" name="file" width="100" accept=".wgt" >
                        <a-button type="primary" @click="uploadFile">上传</a-button>
                    </a-form-item> -->
          <a-form-item label-col-flex="80px" label="更新包" field="file">
            <a-upload action="/" :limit="1" accept=".wgt" :customRequest="customUpload1" />
          </a-form-item>
          <a-form-item label-col-flex="80px" label="安装包" field="file">
            <a-upload action="/" :limit="1" accept=".apk" :customRequest="customUpload2" />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
    <a-modal v-model:visible="visible" @ok="handleOk" hide-cancel ok-text="打印">
      <template #title> 下载二维码 </template>
      <!-- <img :src="'data:image/png;base64,'"/> -->
      <div id="base64Imgs" style="width: 100%; text-align: center">
        <!-- <img :src="base64Img" /> -->
        <QrcodeVue :value="base64Img" style="width: 150px; height: 150px"></QrcodeVue>
      </div>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'
  import emitter from '@/hooks/useEventBus'
  import { ref, reactive, onMounted, toRefs } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Button, Form, Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import { baseURL } from '../../api/axios.config'
  import axios from 'axios'
  import filedownload from 'js-file-download'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  import MyTable from '@/components/MyTable'
  import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
  import { template } from 'lodash'
  import { setupGlobalComponent } from '@/layouts'
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import printJS from 'print-js'
  import QrcodeVue from 'qrcode.vue'

  // 引入

  import { Header } from 'element-plus/es/components/table-v2/src/components'

  interface PositionList {
    id: any
    versionCode: string | undefined
    versionName: string | undefined
    versionInfo: string | undefined
    downloadUrl: string | undefined
    apkUrl: string | undefined
    file: any[]
  }

  export default {
    name: 'VersionManagement',

    setup() {
      const total = ref(0)
      const page = ref(1)
      const size = ref(10)
      function PageSize(val: any) {
        page.value = val
        doRefresh()
      }
      function change1(val: any) {
        size.value = val
        doRefresh()
      }
      const headerShow = ref<boolean>(true)

      function doRefresh() {
        // pageData.pageLoading = true
        // post({
        //   url: 'appVersion/version/getAllVersionPage',
        //   data: {
        //     page: page.value,
        //     size: size.value,
        //   },
        // })
        //   .then(({ data, code }: any) => {
        //     if (code === 200) {
        //       table.handleSuccess(data.list)
        //       // 查询方法改
        //       gridOption.value.setRowData(data.list)
        //       total.value = data.total
        //     }
        //   })
        //   .catch(console.log)
        //   .finally(() => {
        //     pageData.pageLoading = false
        //   })
        try {
          gridOption.value.setQuery({})
        } catch (error) {
          console.log(error)
        }
      }
      const optionsList: any = ref(pagingList)

      const { selectedRowKeys, onSelectionChange } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      const tableColumns = [
        {
          title: '版本号',
          key: 'versionCode',
          dataIndex: 'versionCode',
          width: 150,
        },

        {
          title: '版本名称',
          key: 'versionName',
          dataIndex: 'versionName',
          width: 150,
        },

        {
          title: '版本信息',
          key: 'versionInfo',
          dataIndex: 'versionInfo',
          width: 150,
        },
        {
          title: '更新包路径',
          key: 'downloadUrl',
          dataIndex: 'downloadUrl',
          width: 150,
        },
        {
          title: '安装包路径',
          key: 'apkUrl',
          dataIndex: 'apkUrl',
          width: 150,
        },
        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
          width: 150,
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
          width: 200,
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
          width: 150,
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
          width: 200,
        },
      ]

      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }

        // if (o.slotName === 'versionType') {
        //     obj['resizable'] = false
        //     obj['filter'] = false
        //     obj['sortable'] = false
        //     obj['cellRenderer'] = {
        //         template: `<a-tag color="#f53f3f" v-if="params.data.versionType==1">{{val}}</a-tag><a-tag color="green" v-else>{{val}}</a-tag>`,
        //         setup(props: any) {
        //
        //             let val = ref()
        //             if (props.params.data.versionType == 0) {
        //                 val.value = '内网'
        //             } else {
        //                 val.value = '外网'
        //             }
        //
        //             return {
        //                 val
        //             }
        //         }
        //
        //     }
        // }

        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)
      let configTable = ref({
        url: 'appVersion/version/getAllVersionPage', //接口路径
        queryData: {
          //接口参数
        },
        // isGet:true,//是否是get请求
        // isLimit:true,//后端分页接收limit而非size
        paginationShow: true, //分页是否显示
        invokeiIterface: true, //是否调用接
        rowMultiSelectWithClick: false, //点击行是否多选
        column: tc,
        fileName: 'VersionManagement', //导出文件名
      })
      const pageData = reactive<{
        showAdd: boolean
        sideTitle: string
        nameList: []
        pageLoading: boolean
        typeList: []
        dropDownData1: any
        rHeight: any
        btnList: any[]
        isEdit: boolean
        firmList: any[]
        file: any[]
      }>({
        nameList: [],
        showAdd: false,
        sideTitle: '新增APP版本',
        pageLoading: false,
        typeList: [],
        dropDownData1: '',
        rHeight: 0,
        btnList: [],
        isEdit: false,
        firmList: [],
        file: [],
      })

      onMounted(() => {})
      let cxbl = ''
      //查询
      const selectHandler = () => {
        page.value = 1
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      const addHandler = () => {
        for (var key in dataForm) {
          if (key === 'id') {
            dataForm[key] = null
          } else if (key === 'file') {
            dataForm[key] = []
          } else {
            dataForm[key] = ''
          }
        }

        pageData.showAdd = true
        pageData.sideTitle = '新增APP版本'
      }
      const dataForm = reactive<PositionList>({
        id: null,
        versionCode: '',
        versionName: '',
        versionInfo: '',
        downloadUrl: '',
        apkUrl: '',
        file: [],
      })

      // 表格准备事件
      const gridOption = ref()
      // const gridReady = (params: any) => {
      //   gridOption.value = params.api
      // }

      let formRef = ref<FormInstance>()
      const sideOk = () => {
        formRef.value?.validate().then((err) => {
          if (!err) {
            formRef.value?.validate().then((err) => {
              if (!err) {
                if (pageData.file.length == 0) {
                  Message.error({
                    content: '请上传更新包',
                    duration: 5000,
                  })
                  return
                }
                if (pageData.file[0] == undefined || pageData.file[0] == '空白') {
                  Message.error({
                    content: '请上传更新包',
                    duration: 5000,
                  })
                  return
                }
                pageData.pageLoading = true

                if (pageData.sideTitle === '新增APP版本') {
                  let fd = new FormData()
                  fd.append('file', pageData.file[0])
                  fd.append('file', pageData.file[1])
                  pageData.showAdd = true
                  axios
                    .post(baseURL + '/minio/file/uploadFileBatch', fd, {
                      headers: {
                        'Content-Type': 'multipart/form-data',
                        token: sessionStorage.getItem('USER-TOKEN-KEY'),
                      },
                    })
                    .then((res: any) => {
                      if (res.data.code === 200) {
                        var urlList = res.data.data.data
                        if (urlList.length == 2) {
                          dataForm.apkUrl = urlList[1]
                          dataForm.downloadUrl = urlList[0]
                        } else if (urlList.length == 1) {
                          dataForm.apkUrl = ''
                          dataForm.downloadUrl = urlList[0]
                        } else {
                          dataForm.apkUrl = ''
                          dataForm.downloadUrl = ''
                        }
                        post({
                          url: 'appVersion/version/saveAppVersion',
                          data: dataForm,
                        })
                          .then((res: any) => {
                            if (res.code === 200) {
                              formRef.value?.resetFields()
                              pageData.showAdd = false
                              Message.success({
                                content: '新增成功',
                                duration: 5000,
                              })
                              doRefresh()
                            } else {
                              Message.error({
                                content: res.message,
                                duration: 5000,
                              })
                            }
                          })
                          .finally(() => {
                            pageData.pageLoading = false
                          })
                      } else {
                        Message.error({
                          content: res.message,
                          duration: 5000,
                        })
                      }
                    })
                }
              }
            })
          }
        })
      }

      const deleteHandler = () => {
        if (gridOption.value.getSelectedRows().length === 0) {
          Message.error({
            content: '请勾选数据',
            duration: 5000,
          })
          return
        }

        Modal.confirm({
          title: '系统提示',
          content: '确认删除选中的数据?',
          onOk() {
            pageData.pageLoading = true
            post({
              url: 'appVersion/version/deleteVersion',
              data: gridOption.value.getSelectedRows().map((o: any) => {
                return o.id
              }),
            })
              .then(({ code, data }: any) => {
                if (code === 200) {
                  Message.success({
                    content: '删除成功',
                    duration: 5000,
                  })
                  pagination.page = 1
                  doRefresh()
                } else {
                  Message.error({
                    content: '删除失败',
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          },
        })
      }

      let curobj = null
      const editHandler = (record: PositionList) => {
        curobj = record
        for (let key in record) {
          dataForm[key] = record[key]
        }
        pageData.sideTitle = '修改APP版本'
        pageData.showAdd = true
      }

      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const uploadFile = () => {}
      //文件上传
      function customUpload1(info: any) {
        info.onSuccess('')
        pageData.file[0] = info.fileItem.file

        return info
      }
      function customUpload2(info: any) {
        info.onSuccess('')

        pageData.file[1] = info.fileItem.file
        return info
      }
      //下载安装包
      const downloadApp = () => {
        pageData.pageLoading = true
        post({
          url: 'appVersion/version/downloadNewApk',
        }).then(({ code, data, message }: any) => {
          if (code === 200) {
            axios
              .get(baseURL + data.apkUrl, {
                responseType: 'blob',
                headers: {
                  token: sessionStorage.getItem('USER-TOKEN-KEY'),
                  responseType: 'blob',
                  'Content-Type': 'multipart/from-data',
                },
              })
              .then((res: any) => {
                if (res.status == 200) {
                  const link = document.createElement('a')
                  let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) //生成blob对象
                  link.style.display = 'none'
                  link.href = URL.createObjectURL(blob)
                  //下载的文件名以及文件格式
                  link.setAttribute('download', '巨丰App ' + data.versionCode + '.apk')
                  document.body.appendChild(link)
                  link.click()
                  document.body.removeChild(link)
                }
              })
              .catch(() => {
                Message.error({
                  content: '文件路径不存在，请联系管理员.',
                  duration: 5000,
                })
              })
              .finally(() => {
                pageData.pageLoading = false
              })
          } else {
            Message.error({
              content: message,
              duration: 5000,
            })
          }
        })
      }

      const localeText1: any = ref(localeText)
      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()

      if (permissionStore.hasPermisson('appbbgl.cx')) {
        pageData.btnList.push('查询')
      }
      if (permissionStore.hasPermisson('appbbgl.xz')) {
        pageData.btnList.push('新增')
      }
      if (permissionStore.hasPermisson('appbbgl.sc')) {
        pageData.btnList.push('删除')
      }
      if (permissionStore.hasPermisson('appbbgl.xzazb')) {
        pageData.btnList.push('下载安装包')
        pageData.btnList.push('下载二维码')
      }

      const visible = ref(false)

      const downloadAppQrcodes = () => {
        // get({
        //   url: 'appVersion/version/getNewApkQRCode',
        // }).then((res: any) => {
        //   if (res.code == 200) {
        //     base64Img.value = res.data
        //     visible.value = true
        //   }
        // })
        base64Img.value = `${window.location.protocol}//${window.location.host}/procoderDownApp.html`
        visible.value = true
      }

      const handleOk = () => {
        printJS({
          printable: 'base64Imgs',
          type: 'html',
          font_size: '',
          targetStyles: ['*'],
        })
        visible.value = false
      }

      const base64Img = ref('')

      return {
        base64Img,
        handleOk,
        visible,
        downloadAppQrcodes,
        localeText1,
        downloadApp,
        customUpload1,
        customUpload2,
        uploadFile,
        defaultColDef,
        tc,
        total,
        PageSize,
        change1,
        page,
        size,
        editHandler,
        deleteHandler,
        sideOk,
        formRef,
        dataForm,
        addHandler,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        selectHandler,
        headerShow,
        handleChange,
        // gridReady,
        gridOption,
        optionsList,
        configTable,
      }
    },
    components: { Toolbar, PageTabelLayout, QrcodeVue },
  }
</script>
<style scoped lang="less">
  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }
</style>
